package dobest.ray.com.jiongjiong.activity.mumingleshi;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dobest.ray.corelibs.utils.ToastMgr;
import com.dobest.ray.corelibs.views.NoScrollingListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import dobest.ray.com.jiongjiong.R;
import dobest.ray.com.jiongjiong.activity.BaseActivity;
import dobest.ray.com.jiongjiong.adapter.BindDevicesListAdapter;
import dobest.ray.com.jiongjiong.bean.BindDeviceBean;
import dobest.ray.com.jiongjiong.utils.ACacheHelper;
import dobest.ray.com.jiongjiong.views.NavigationBar;

/**
 * Created by Ray on 2016/3/15.
 * https://github.com/ray0807
 */
public class BindDeviceActivity extends BaseActivity implements View.OnClickListener {
    private NoScrollingListView ls_devices;
    private NoScrollingListView ls_can_bind_devices;
    private BindDevicesListAdapter adapter;
    private BindDeviceBean bean;

    private TextView tv_stop_or_start_research;

    private LinearLayout ll_stop_search;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_devices);
        findViews();
        init();
        addListeners();
    }

    @Override
    public void findViews() {
        navi = (NavigationBar) findViewById(R.id.navi);
        navi.setTitle("绑定设备");
        navi.setBackListener(this, R.mipmap.img_back);
        ls_devices = (NoScrollingListView) findViewById(R.id.ls_devices);
        ls_can_bind_devices = (NoScrollingListView) findViewById(R.id.ls_can_bind_devices);

        tv_stop_or_start_research = (TextView) findViewById(R.id.tv_stop_or_start_research);
        ll_stop_search = (LinearLayout) findViewById(R.id.ll_stop_search);

        bean = ACacheHelper.getInstance().getBindDevices(BindDeviceActivity.this);


    }

    @Override
    public void init() {
        adapter = new BindDevicesListAdapter(this);
        ls_devices.setAdapter(adapter);
        if (bean != null) {
            adapter.addData(bean);
        }
        initBle();
    }

    @Override
    public void addListeners() {
        ls_can_bind_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = list.get(position);
                mDeviceName = device.getName();
                mDeviceAddress = device.getAddress();
                bindService(gattServiceIntent, mServiceConnection,
                        BIND_AUTO_CREATE);
                if (mBluetoothLeService != null) {
                    final boolean result = mBluetoothLeService
                            .connect(mDeviceAddress);
                }
                BleAdapter.remove(position);

            }
        });
        tv_stop_or_start_research.setOnClickListener(this);
    }

    private boolean isSearch = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_back_operate:
                finish();
                break;
            case R.id.tv_stop_or_start_research:
                if (isSearch) {
                    bluetoothAdapter.stopLeScan(mLeScanCallback);
                    ll_stop_search.setVisibility(View.GONE);
                    tv_stop_or_start_research.setText("开始查找");
                    isSearch = false;
                } else {
                    bluetoothAdapter.startLeScan(mLeScanCallback);
                    ll_stop_search.setVisibility(View.VISIBLE);
                    tv_stop_or_start_research.setText("停止查找");
                    isSearch = true;
                }
                break;
        }
    }

    //-----蓝牙----------
    private BluetoothLeService mBluetoothLeService;
    private String mDeviceName;
    private String mDeviceAddress;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private boolean mConnected;
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    private final String LIST_NAME = "NAME";
    private final String LIST_UUID = "UUID";
    private Intent gattServiceIntent;
    private BluetoothAdapter bluetoothAdapter;
    private ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
    private boolean isBindServiece = false;
    private LeDeviceListAdapter BleAdapter;

    private void initBle() {
        gattServiceIntent = new Intent(this, BluetoothLeService.class);
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            ToastMgr.show("不支持蓝牙");
        }

        // 获得蓝牙管理器
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
            }
        }
        BleAdapter = new LeDeviceListAdapter(
                BindDeviceActivity.this, list);
        ls_can_bind_devices.setAdapter(BleAdapter);
        bluetoothAdapter.startLeScan(mLeScanCallback);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter
                .addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 扫描到后添加然后刷新
                    Log.i("wanglei", "device:" + device.getName());
                    BleAdapter.notifyDataSetChanged();
                    if (!(list.contains(device) || (bean != null && bean.deviceName.equals(device.getName()) && bean.deviceMac.equals(device.getAddress())))) {
                        list.add(device);
                    }
                }
            });
        }
    };


    // 服务链接
    ServiceConnection mServiceConnection = new ServiceConnection() {

        // 链接服务
        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initialize()) {
                finish();
            }

            isBindServiece = true;
            // 链接设备
            boolean flag = mBluetoothLeService.connect(mDeviceAddress);
            Log.i("wanglei", "flag:" + flag);
            if (flag) {
                ToastMgr.show("链接成功");
            }
        }

        // 断开服务
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
            ToastMgr.show("断开连接");
            isBindServiece = false;
        }
    };

    // 广播接受 者
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            // 如果已经链接了
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                ToastMgr.show("绑定成功");
                BindDeviceBean bean = new BindDeviceBean(mDeviceName, mDeviceAddress);
                ACacheHelper.getInstance().saveBindDevices(BindDeviceActivity.this, bean);
                adapter.addData(bean);

                // 如果没有链接
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
                    .equals(action)) {
                ToastMgr.show("链接失败");

                // 如果发现服务
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                    .equals(action)) {
                displayGattServices(mBluetoothLeService
                        .getSupportedGattServices());
                //发送指令
                // getStartData();


                // 有用的数据
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                String str = intent
                        .getStringExtra(BluetoothLeService.EXTRA_DATA);
                String[] stringByte = str.split(" ");
                if (stringByte.length == 20) {
                    //接收蓝牙设备返回数据
                }
            }
        }
    };

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null)
            return;
        String uuid = null;
        String unknownServiceString = getResources().getString(
                R.string.unknown_service);
        String unknownCharaString = getResources().getString(
                R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData = new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(LIST_NAME,
                    SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                    .getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(LIST_NAME,
                        SampleGattAttributes.lookup(uuid, unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
    }


    private class LeDeviceListAdapter extends BaseAdapter {
        ArrayList<BluetoothDevice> list;
        Context context;

        public LeDeviceListAdapter(Context context,
                                   ArrayList<BluetoothDevice> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (view == null) {
                viewHolder = new ViewHolder();
                view = View.inflate(context, R.layout.list_item_device, null);
                viewHolder.deviceAddress = (TextView) view
                        .findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view
                        .findViewById(R.id.device_name);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            BluetoothDevice device = list.get(i);
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();
            if (deviceName != null && deviceName.length() > 0) {
                viewHolder.deviceName.setText(deviceName);
            }

            if (deviceName != null && deviceName.length() > 0) {
                viewHolder.deviceAddress.setText(deviceAddress);
            }

            return view;
        }

        public void remove(int position) {
            list.remove(position);
            notifyDataSetChanged();
        }
    }

    static class ViewHolder {
        TextView deviceName;
        TextView deviceAddress;
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mGattUpdateReceiver);
        bluetoothAdapter.stopLeScan(mLeScanCallback);
//        bluetoothAdapter.disable();
        if (isBindServiece) {
            unbindService(mServiceConnection);
        }
        mBluetoothLeService = null;
        super.onDestroy();
    }




}
